import enquireJs from "enquire.js";
import storage from 'store'
const XLSX = require('xlsx');
import Vue from 'vue'

export function isDef(v) {
  return v !== undefined && v !== null;
}
/**
 * 把文件按照二进制进行读取
 * @param {Object} file
 * @returns
 */
export function readFile(file) {
  return new Promise(resolve=>{
    let reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.onload = ev =>{
      resolve(ev.target?.result);
    }
  });
}

/**
 * 根据sheet索引读取Excel文件中的数据
 * @param {Object} file 文件
 * @param {Number} sheetIndex excel文件中sheet表索引 默认是从0开始
 * @returns  将表中的数据以json形式的数据返回
 */
export async function  readExcelFile(file,sheetIndex)
{
  let data = await readFile(file);
  let workbook = XLSX.read(data,{type:'binary'});
  let worksheet = workbook.Sheets[workbook.SheetNames[sheetIndex]];
  data = XLSX.utils.sheet_to_json(worksheet);
  return data;
}
/**
 * 获取时间戳
 * @returns {string}
 */
export function getTimestamp() {
  const timestamp = (Date.parse(new Date()) + "").substr(0, 10);
  return timestamp;
}
/**
 * 深拷贝（数组、对象或数组对象）
 */
export function deepClone (obj) {
  var newObj = obj.constructor === Array ? [] : {}
  if (typeof obj !== 'object') {
    return;
  }
  for (const i in obj) {
    newObj[i] = (obj[i] && typeof obj[i] === 'object') ? deepClone(obj[i]) : obj[i]
  }
  return newObj
}
/**
 * Remove an item from an array.
 */
export function remove(arr, item) {
  if (arr.length) {
    const index = arr.indexOf(item);
    if (index > -1) {
      return arr.splice(index, 1);
    }
  }
}

export function timeFix () {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
}

/**
 * 获取stroge数据
 * @returns {string}
 */
export function getUserInformation (informationName) {
  const data = storage.get(informationName)
  return data
}

export function isRegExp(v) {
  return _toString.call(v) === "[object RegExp]";
}

export function enquireScreen(call) {
  const handler = {
    match: function() {
      call && call(true);
    },
    unmatch: function() {
      call && call(false);
    }
  };
  enquireJs.register("only screen and (max-width: 767.99px)", handler);
}

export function uuid() {
  let s = [];
  let hexDigits = "0123456789abcdef";
  for (let i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-";

  let uuid = s.join("");
  return uuid;
}

/**
 * 两个浮点数求和
 * @param num1
 * @param num2
 * @return {number}
 */
export function accAdd(num1, num2) {
  // eslint-disable-next-line one-var
  let r1 = 0, r2 = 0
  try {
    r1 = (num1.toString().split('.')[1] || []).length
  } catch (e) {
    return num1 + num2
  }
  try {
    r2 = (num2.toString().split('.')[1] || []).length
  } catch (e) {
    return num1 + num2
  }
  const m = Math.pow(10, Math.max(r1, r2))
  return Math.round(accMul(num1, m) + accMul(num2, m)) / m
}

/**
 * 两个浮点数相减
 * @param num1
 * @param num2
 * @return {number}
 */
export function accSub(num1, num2) {
  let r1, r2
  try {
    r1 = (num1.toString().split('.')[1] || []).length
  } catch (e) {
    return num1 - num2
  }
  try {
    r2 = (num2.toString().split('.')[1] || []).length
  } catch (e) {
    return num1 - num2
  }
  const m = Math.pow(10, Math.max(r1, r2))
  return Math.round(accMul(num1, m) - accMul(num2, m)) / m
}

/**
 * 两个浮点数相乘
 * @param num1
 * @param num2
 * @return {number}
 */
export function accMul(num1, num2) {
  let m = 0
  const s1 = num1.toString()
  const s2 = num2.toString()
  try {
    m += (s1.split('.')[1] || []).length
  } catch (e) {
    return num1 * num2
  }
  try {
    m += (s2.split('.')[1] || []).length
  } catch (e) {
    return num1 * num2
  }
  return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m)
}

/**
 * 两个浮点数相除
 * @param num1
 * @param num2
 * @return {number}
 */
export function accDiv(num1, num2) {
  let m = 0
  const s1 = num1.toString()
  const s2 = num2.toString()
  try {
    m += (s1.split('.')[1] || []).length
  } catch (e) {
    return num1 / num2
  }
  try {
    m += (s2.split('.')[1] || []).length
  } catch (e) {
    return num1 / num2
  }
  const n1 = accMul(num1, Math.pow(10, m))
  const n2 = accMul(num2, Math.pow(10, m))
  return Number(n1) / Number(n2)
}

/**
 * 数组对象去重，uniId为对象属性(数组形式传参)
 * @param arr
 * @param uniId
 * @return {list}
 */
export function uniqueReduce (arr, uniId) {
  const hasObj = {}
  return arr.reduce((total, next) => {
    var filterKey = ''
    uniId.forEach(item => {
      filterKey = filterKey + next[item]
    })
    // eslint-disable-next-line no-unused-expressions
    hasObj[filterKey] ? '' : hasObj[filterKey] = true && total.push(next)
    return total
  }, [])
}

/**
 * 将大额数字转换为万、千万、亿等,并保留2位小数（type为1时少于一万不精确到小数点）
 * @param value
 * @param type
 * @return {object}
 */
export function bigNumberTransform (value, type) {
  let param = {};
  let k = 10000,
    sizes = ['', '万', '亿', '万亿'],
    i;
  if(value < k){
    if (type === 1) {
      param.value =value
    } else {
      param.value =value.toFixed(2)
    }
    param.unit=''
  }else{
    i = Math.floor(Math.log(value) / Math.log(k));
    param.value = ((value / Math.pow(k, i))).toFixed(2);
    param.unit = sizes[i];
  }
  return param;
}

/**
 * 对象数组排序（根据对象的某个属性）
 * 使用示例：this.data.sort(this.compare('quantity'))
 * @param {string} propertyName
 * @return {list}
 */
export function compare (propertyName){
  return function(object1,object2){
    var value1 = object1[propertyName];
    var value2 = object2[propertyName];
    if(value1 < value2){
      return -1;
    }else if(value1 > value2){
      return 1;
    }else{
      return 0;
    }
  }
}
/**
 * @description: 下载文件
 * @param {string} data 文件流
 * @param {string} filename 文件名
 * @param {string} type 文件格式
 * @param {boolean} isDownLoad 是否立即自动下载(true:点击立即下载，false:点击打开预览，手动下载)
 * @return {*}
 */
export function downloadFile(data, filename, isDownLoad,type) {
  const randomFileName = Math.random().toString(36).substring(7);
  const blob = new Blob([data], { type: 'application/'+type+';charset-UTF-8' })
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  link.target = '_blank'
  link.setAttribute('id', 'ID')
  if (isDownLoad) {
    if (filename) {
      link.setAttribute('download', filename)
    } else {
      link.setAttribute('download', `file_${randomFileName}.`+type)
    }
  }
  document.body.appendChild(link)
  link.click()
  setTimeout(() => {
    document.body.removeChild(link)
    if (isDownLoad) {
      window.URL.revokeObjectURL(url)
    }
  }, 10)
}
/**
 * @description: 判断对象数组是否已发生改变（注意：此方法去判断两个数组的全部属性必须保持一致，若对象属性发生增减修改，则此方法无法进行判断）
 * @param {array} oldData 原数组
 * @param {array} newData 新数组
 * @return {boolean}
 */
export function arrayChanged (oldData,newData ) {
  let isArrayChanged = newData.some(function(item, index) {
    return JSON.stringify(item) !== JSON.stringify(oldData[index])
  })
  return isArrayChanged; // 如果数组和原来的不一样，返回true
}

export function deepCopy(target) {
  if (typeof target == 'object') {
    const result = Array.isArray(target) ? [] : {}
    for (const key in target) {
      if (typeof target[key] == 'object') {
        result[key] = deepCopy(target[key])
      } else {
        result[key] = target[key]
      }
    }

    return result
  }

  return target
}

export function swap(arr, i, j) {
  const temp = arr[i]
  Vue.set(arr, i, arr[j])
  Vue.set(arr, j, temp)
}

export function $(selector) {
  return document.querySelector(selector)
}

const components = ['VText', 'RectShape', 'CircleShape']
export function isPreventDrop(component) {
  return !components.includes(component) && !component.startsWith('SVG')
}

// 字符串转base64
export function strToBase(str) {
  // 对字符串进行编码
  var encode = encodeURI(str)
  // 对编码的字符串转化base64
  var base64 = btoa(encode)
  return base64
}
// base64转字符串
export function baseToStr(base64) {
  // 对base64转编码
  var decode = atob(base64)
  // 编码转字符串
  var str = decodeURI(decode)
  return str
}
export function formatDateToString(d) {
  /**
   * 格式化时间（YYYYMMddHHmmss）
   */
  let date = null
  if (d === undefined || d === null || d === '') {
    date = new Date()
  } else { date = new Date(d) }
  let year = date.getFullYear().toString()
  let month = (date.getMonth() + 1).toString()
  let day = date.getDate().toString()
  let hour = date.getHours().toString()
  let minute = date.getMinutes().toString()
  let second = date.getSeconds().toString()
  year = year[1] ? year : '0' + year
  month = month[1] ? month : '0' + month
  day = day[1] ? day : '0' + day
  hour = hour[1] ? hour : '0' + hour
  minute = minute[1] ? minute : '0' + minute
  second = second[1] ? second : '0' + second
  return (''+year+month+day+hour+minute+second)
}
export function formatDateTime(d) {
  /**
   * 格式化时间（YYYY-MM-dd HH:mm:ss）
   */
  let date = null
  if (d === undefined || d === null || d === '') {
    date = new Date()
  } else { date = new Date(d) }
  let year = date.getFullYear().toString()
  let month = (date.getMonth() + 1).toString()
  let day = date.getDate().toString()
  let hour = date.getHours().toString()
  let minute = date.getMinutes().toString()
  let second = date.getSeconds().toString()
  year = year[1] ? year : '0' + year
  month = month[1] ? month : '0' + month
  day = day[1] ? day : '0' + day
  hour = hour[1] ? hour : '0' + hour
  minute = minute[1] ? minute : '0' + minute
  second = second[1] ? second : '0' + second
  return ([year, month, day].join('-') + ' ' + [hour, minute, second].join(':'))
}
export function formatDate(d) {
  /**
   * 格式化时间（YYYY-MM-dd）
   */
  let date = null
  if (d === undefined || d === null || d === '') {
    date = new Date()
  } else { date = new Date(d) }
  let year = date.getFullYear().toString()
  let month = (date.getMonth() + 1).toString()
  let day = date.getDate().toString()
  year = year[1] ? year : '0' + year
  month = month[1] ? month : '0' + month
  day = day[1] ? day : '0' + day
  return ([year, month, day].join('-'))
}
export function formatDateZH(d) {
  /**
   * 格式化时间（YYYY年MM月dd日）
   */
  let date = null
  if (d === undefined || d === null || d === '') {
    date = new Date()
  } else { date = new Date(d) }
  let year = date.getFullYear().toString()
  let month = (date.getMonth() + 1).toString()
  let day = date.getDate().toString()
  year = year[1] ? year : '0' + year
  month = month[1] ? month : '0' + month
  day = day[1] ? day : '0' + day
  return (year+'年'+month+'月'+day+'日')
}

const _toString = Object.prototype.toString;
